﻿
using System.Text;

namespace IdentityWebApi
{
    /// <summary>
    /// 后台服务，每隔5秒执行一次
    /// </summary>
    public class ExplortStaticBgService : BackgroundService
    {
        private readonly MySqlDbContext _dbContext;
        private readonly ILogger<ExplortStaticBgService> _logger;
        private readonly IServiceScope _serviceScope;
        public ExplortStaticBgService(IServiceScopeFactory serviceScopeFactory)
        {
            // 使用依赖注入获取DbContext还是需要使用IServiceScopeFactory
            this._serviceScope = serviceScopeFactory.CreateScope();
            var sp = _serviceScope.ServiceProvider;
            _dbContext = sp.GetRequiredService<MySqlDbContext>();
            _logger = sp.GetRequiredService<ILogger<ExplortStaticBgService>>();
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    await DoExecuteAsync();
                    await Task.Delay(5000, stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "导出失败");
                    await Task.Delay(5000, stoppingToken);
                }
            }
        }

        private async Task DoExecuteAsync()
        {
            var items = _dbContext.Users.GroupBy(u=>u.CreateTime.Date)
                .Select(e=>new
                {
                    Date = e.Key,
                    Count = e.Count()
                }).ToList();
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"Date:{DateTime.Now}");
            foreach (var item in items)
            {
                sb.AppendLine($"Date:{item.Date},Count:{item.Count}");
            }
            var path = Path.Combine(AppContext.BaseDirectory, "test2.txt");
            await File.WriteAllTextAsync(path, sb.ToString());
            _logger.LogInformation("导出成功");
        }

        public override void Dispose()
        {
            base.Dispose();
            _serviceScope.Dispose();
        }
    }
}
